/**
 * Edge浏览器应急修复脚本
 * 可以通过控制台快速执行的修复工具
 */

export class EdgeEmergencyFix {
  /**
   * 全面清理Edge缓存和状态
   */
  static async fullCleanup(): Promise<void> {
    // console.log('🚑 开始Edge应急修复...');

    try {
      // 1. 清理所有localStorage
      // console.log('🧹 清理localStorage...');
      const userDataBackup = localStorage.getItem('userData');
      localStorage.clear();
      if (userDataBackup) {
        localStorage.setItem('userData', userDataBackup);
        // console.log('✅ 用户数据已备份恢复');
      }

      // 2. 清理sessionStorage
      // console.log('🧹 清理sessionStorage...');
      sessionStorage.clear();

      // 3. 清理Service Worker缓存
      if ('serviceWorker' in navigator) {
        const registrations = await navigator.serviceWorker.getRegistrations();
        for (let registration of registrations) {
          await registration.unregister();
          // console.log('🧹 清理Service Worker:', registration.scope);
        }
      }

      // 4. 清理Cache API
      if ('caches' in window) {
        const cacheNames = await caches.keys();
        for (let cacheName of cacheNames) {
          await caches.delete(cacheName);
          // console.log('🧹 清理Cache:', cacheName);
        }
      }

      // 5. 强制重新加载CSS
      const links = document.querySelectorAll('link[rel="stylesheet"]');
      links.forEach((link: any) => {
        const href = link.href;
        link.href = href + (href.includes('?') ? '&' : '?') + '_edge_refresh=' + Date.now();
      });

      // console.log('✅ Edge应急修复完成，建议刷新页面');

    } catch (error) {
      // console.error('❌ Edge应急修复失败:', error);
      console.error('Edge emergency fix failed', error);
    }
  }

  /**
   * 快速重置网络配置
   */
  static resetNetworkConfig(): void {
    // console.log('🌐 重置Edge网络配置...');

    const hostname = window.location.hostname;
    const isNetworkAccess = hostname !== 'localhost' && hostname !== '127.0.0.1';

    // 设置正确的API配置
    (window as any).EDGE_API_CONFIG = {
      isNetworkAccess,
      apiBase: isNetworkAccess
        ? `${window.location.protocol}//${hostname}:8000`
        : 'http://127.0.0.1:8000'
    };

    // console.log('✅ 网络配置已重置:', (window as any).EDGE_API_CONFIG);
  }

  /**
   * 手动设置API地址
   */
  static setApiUrl(url: string): void {
    // console.log('🔧 手动设置API地址:', url);

    (window as any).EDGE_API_CONFIG = {
      isNetworkAccess: true,
      apiBase: url
    };

    // 更新localStorage中的配置
    localStorage.setItem('manual_api_url', url);

    // console.log('✅ API地址已设置，建议刷新页面');
  }

  /**
   * 测试API连接
   */
  static async testApiConnection(): Promise<void> {
    const apiBase = (window as any).EDGE_API_CONFIG?.apiBase || 'http://127.0.0.1:8000';

    // console.log('🔍 测试API连接:', apiBase);

    try {
      // 测试健康检查端点
      const response = await fetch(`${apiBase}/health`, {
        method: 'GET',
        mode: 'cors',
        cache: 'no-cache'
      });

      if (response.ok) {
        // console.log('✅ API连接成功');
      } else {
        // console.log('⚠️ API响应异常:', response.status, response.statusText);
      }
    } catch (error) {
      // console.error('❌ API连接失败:', error);
      console.error('API connection failed', error);

      // 尝试备用测试
      try {
        const optionsResponse = await fetch(apiBase, {
          method: 'OPTIONS',
          mode: 'cors',
          cache: 'no-cache'
        });
        // console.log('ℹ️ OPTIONS请求结果:', optionsResponse.status);
      } catch (optionsError) {
        // console.error('❌ OPTIONS请求也失败:', optionsError);
        console.error('OPTIONS request failed', optionsError);
      }
    }
  }

  /**
   * 获取诊断信息
   */
  static getDiagnostics(): any {
    const userAgent = navigator.userAgent;
    const isEdge = /Edge\//.test(userAgent) || /Edg\//.test(userAgent);
    const hostname = window.location.hostname;

    return {
      browser: {
        userAgent,
        isEdge,
        version: isEdge ? userAgent.match(/Edg?\/(\d+)/)?.[1] : 'N/A'
      },
      network: {
        hostname,
        protocol: window.location.protocol,
        port: window.location.port,
        isNetworkAccess: hostname !== 'localhost' && hostname !== '127.0.0.1'
      },
      api: {
        config: (window as any).EDGE_API_CONFIG,
        manualUrl: localStorage.getItem('manual_api_url')
      },
      cache: {
        localStorageKeys: Object.keys(localStorage),
        sessionStorageKeys: Object.keys(sessionStorage)
      },
      timestamp: new Date().toISOString()
    };
  }
}

// 在控制台中提供快捷命令
if (typeof window !== 'undefined') {
  (window as any).edgeEmergencyFix = EdgeEmergencyFix;

  // 检测Edge浏览器并显示帮助信息
  const isEdge = /Edge\//.test(navigator.userAgent) || /Edg\//.test(navigator.userAgent);
  if (isEdge) {
    //     console.log(`
    // 🔧 Edge浏览器修复工具已加载！

    // 快捷命令：
    // • edgeEmergencyFix.fullCleanup()     - 全面清理缓存
    // • edgeEmergencyFix.resetNetworkConfig() - 重置网络配置  
    // • edgeEmergencyFix.testApiConnection()   - 测试API连接
    // • edgeEmergencyFix.getDiagnostics()      - 获取诊断信息
    // • edgeEmergencyFix.setApiUrl('http://192.168.31.86:8000') - 手动设置API地址

    // 如果遇到问题，请先尝试 fullCleanup() 然后刷新页面。
    //     `);
  }
} 